package com.shoulder.feign.interceptor;

import com.shoulder.core.enums.HeaderEnums;
import com.shoulder.core.utils.LogTraceUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;


import jakarta.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class ClientRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String header = request.getHeader(HeaderEnums.BEARER_HEADER.getCode());
            if (header != null) {
                template.header(HeaderEnums.BEARER_HEADER.getCode(), header);
            }

            String basic = request.getHeader(HeaderEnums.BASIC_HEADER.getCode());
            if (basic != null) {
                template.header(HeaderEnums.BASIC_HEADER.getCode(), basic);
            }

            String traceId = request.getHeader(LogTraceUtils.TRACE_ID);
            if (traceId == null) {
                traceId = LogTraceUtils.get();
            }
            if (StringUtils.hasText(traceId)) {
                template.header(LogTraceUtils.TRACE_ID, traceId);
            }

        }
    }
}
